package com.linkage.educloud.ah.view.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linkage.educloud.ah.MyApplication;
import com.linkage.educloud.ah.R;
import com.linkage.educloud.ah.adapter.AppClassifyAdapter;
import com.linkage.educloud.ah.adapter.AppMainResAdapter;
import com.linkage.educloud.ah.adapter.HomeResAdapter;
import com.linkage.educloud.ah.bean.AccountData;
import com.linkage.educloud.ah.bean.AppClassify;
import com.linkage.educloud.ah.bean.HomeResBean;
import com.linkage.educloud.ah.bean.ResClassify;
import com.linkage.educloud.ah.bean.ResClassifyMeta;
import com.linkage.educloud.ah.bean.StudyTypeBean;
import com.linkage.educloud.ah.config.AccountConfig;
import com.linkage.educloud.ah.mvp.contract.IAppContract;
import com.linkage.educloud.ah.mvp.presenter.AppPresenter;
import com.linkage.educloud.ah.view.BasicTitleFragment;
import com.linkage.educloud.ah.view.activity.app.SubjectTypeActivity;
import com.linkage.educloud.ah.widget.MyMore;
import com.linkage.educloud.ah.widget.NoScrollGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class AppFragment extends BasicTitleFragment implements View.OnClickListener, IAppContract.IView {

    @BindView(R.id.fragment_app_search)
    TextView fragment_app_search;
    @BindView(R.id.fragment_app_grid_apptype)
    NoScrollGridView fragment_app_grid_apptype;
    @BindView(R.id.fragment_app_radiogroup)
    RadioGroup fragment_app_radiogroup;
    @BindView(R.id.fragment_app_more_restype)
    TextView fragment_app_more_restype;
    @BindView(R.id.fragment_app_gird_res)
    GridView fragment_app_gird_res;
    @BindView(R.id.fragment_app_more_jszx)
    MyMore fragment_app_more_jszx;
    @BindView(R.id.fragment_app_tab_subject)
    TabLayout fragment_app_tab_subject;
    @BindView(R.id.fragment_app_list_resources)
    XRecyclerView fragment_app_list_resources;

    private AccountData accountData;
    private IAppContract.IPresenter iPresenter;
    private List<ResClassifyMeta> mClassifyMetas;
    private int defaultGradeId = 13;
    private int defaultSelectSubject = 0;
    private boolean isReChoose = false;//加个标记位，表示切换班级返回调用的，过滤掉tab添加数据时默认定位到0位后，切换到目标位后重复请求的问题。只有班级改变为true
    private List<HomeResBean> homeResBeanList = new ArrayList<>();
    private HomeResAdapter homeResAdapter;
    private int page = 1;

    public static AppFragment newInstance() {
        AppFragment fragment = new AppFragment();
        return fragment;
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_app;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        accountData = AccountConfig.getLoginAccount();
        iPresenter = new AppPresenter(getActivity(), this);
        if (accountData.getUserType() == 1) {
            setTitle("教学");
        } else {
            setTitle("学习");
        }
        initRecylerview();
        iPresenter.getAppClassify();
        iPresenter.getResClassify();
        iPresenter.getRecommends(defaultSelectSubject, defaultGradeId, page);

        fragment_app_radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = (RadioButton) group.getChildAt(checkedId);
                if (radioButton == null || "最后一课".endsWith(radioButton.getText().toString())) {
                    fragment_app_more_restype.setVisibility(View.GONE);
                } else {
                    fragment_app_more_restype.setVisibility(View.VISIBLE);
                }
                setGridView(mClassifyMetas.get(checkedId - 1000).getResClassifies());
            }
        });

        fragment_app_tab_subject.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (isReChoose) {
                    isReChoose = false;
                    return;
                }
                defaultSelectSubject = (Integer) tab.getTag();
                page = 1;
                iPresenter.getRecommends(defaultSelectSubject, defaultGradeId, page);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void initAppClassify(List<AppClassify> list) {
        fragment_app_grid_apptype.setAdapter(new AppClassifyAdapter(getActivity(), list));
    }

    public void initRadioButton(List<ResClassifyMeta> classifyMetas) {
        mClassifyMetas = classifyMetas;
        fragment_app_radiogroup.removeAllViews();
        for (int i = 0; i < mClassifyMetas.size(); i++) {
            ResClassifyMeta meta = mClassifyMetas.get(i);
            RadioButton button = (RadioButton) LayoutInflater.from(getActivity()).inflate(R.layout.radiobutton_fragment_app, null);
            ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.setMargins(8, 0, 8, 0);
            button.setTextSize(15);
            if (meta.getClassifyType() == 0) {//0为合肥一中，1为最后一课
                button.setText("合肥一中  ");
                button.setChecked(true);
                button.setId(1000 + i);
            } else if (meta.getClassifyType() == 1) {
                button.setText("最后一课  ");
                button.setChecked(false);
                button.setId(1000 + i);
            }
            fragment_app_radiogroup.addView(button, lp);
            if (i != mClassifyMetas.size() - 1) {
                TextView textView = new TextView(getActivity());
                textView.setText("|  ");
                textView.setTextColor(getActivity().getResources().getColor(R.color.black));
                fragment_app_radiogroup.addView(textView, lp);
            }
        }
        if (fragment_app_radiogroup.getChildCount() > 0) {
            fragment_app_radiogroup.check(1000 + 0);
        }
    }

    //设置横向滚动数据
    private void setGridView(List<ResClassify> resClassifys) {
        if (resClassifys == null) {
            return;
        }
        int size = resClassifys.size();
        int length = 140;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * (length + 10) * density);
        int itemWidth = (int) (length * density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth + 10 * size, LinearLayout.LayoutParams.FILL_PARENT);
        fragment_app_gird_res.setLayoutParams(params);
        fragment_app_gird_res.setColumnWidth(itemWidth);
        fragment_app_gird_res.setHorizontalSpacing(10);
        fragment_app_gird_res.setStretchMode(GridView.NO_STRETCH);
        fragment_app_gird_res.setNumColumns(size);
        fragment_app_gird_res.setAdapter(new AppMainResAdapter(getActivity(), resClassifys));
    }

    public void initSubjectTab(final List<StudyTypeBean> studyTypes) {
        if (accountData.getOrigin() == 1) {
            defaultGradeId = 13;//注册用户默认取初三的数据，不要问我为什么，产品要求的。
        } else {
            if (accountData.getUserType() == 1) {
                defaultGradeId = accountData.getGradetype();
            } else {
                defaultGradeId = MyApplication.getInstance().getResovler().getChild(accountData.getLoginAccount()).get(0).getGradeid();//默认取第一个孩子的年级id
            }
        }

        for (int i = 0; i < studyTypes.size(); i++) {
            StudyTypeBean stu = studyTypes.get(i);
            if (stu.getId() == defaultGradeId) {
                fragment_app_more_jszx.setRightText(stu.getName());
                fragment_app_tab_subject.removeAllTabs();
                fragment_app_tab_subject.addTab(fragment_app_tab_subject.newTab().setText("全部").setTag(0), 0);
                for (int j = 0; j < stu.getSubjects().size(); j++) {
                    fragment_app_tab_subject.addTab(fragment_app_tab_subject.newTab().setText(stu.getSubjects().get(j).getName()).setTag(stu.getSubjects().get(j).getId()), j + 1);
                }
                return;
            }
        }

        fragment_app_more_jszx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SubjectTypeActivity.launch(getActivity(), studyTypes);
            }
        });
    }

    private void initRecylerview() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fragment_app_list_resources.setLayoutManager(layoutManager);
        fragment_app_list_resources.setItemAnimator(new DefaultItemAnimator());
        fragment_app_list_resources.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        fragment_app_list_resources.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);

        fragment_app_list_resources.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                page = 1;
                iPresenter.getRecommends(defaultSelectSubject, defaultGradeId, page);
            }

            @Override
            public void onLoadMore() {
                page++;
                iPresenter.getRecommends(defaultSelectSubject, defaultGradeId, page);
            }
        });

        homeResAdapter = new HomeResAdapter(getActivity(), homeResBeanList);
        fragment_app_list_resources.setAdapter(homeResAdapter);
    }

    public void initReslist(String title, List<HomeResBean> mlist) {
        fragment_app_more_jszx.setLeftText(title);
        if (mlist.size() < 10) {
            fragment_app_list_resources.setLoadingMoreEnabled(false);
        } else {
            fragment_app_list_resources.setLoadingMoreEnabled(true);
        }
        homeResAdapter.addAll(mlist, page != 1);
    }

    public void stopRefresh() {
        fragment_app_list_resources.refreshComplete();
        fragment_app_list_resources.loadMoreComplete();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_app_more_jszx:

                break;
        }
    }
}